package cn.aitrox.ry.common.service.api.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class FeignRequestInterceptor implements RequestInterceptor {

    private static final String USER = "User";

    @Override
    public void apply(RequestTemplate template) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes attr = (ServletRequestAttributes) requestAttributes;
        if(null == attr) {
            return;
        }
        HttpServletRequest request = attr.getRequest();
        String userStr = request.getHeader(USER);//网关或者传过来的userInfo
        if (StringUtils.isNotEmpty(userStr)) {
            template.header(USER, userStr);
        }
    }
}
